package com.zhangxx.common.exception;

import com.google.common.collect.ImmutableMap;
import com.zhangxx.common.response.ResponseResult;
import com.zhangxx.common.response.resultCode.CommonCode;
import com.zhangxx.common.response.resultCode.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @ClassName ExceptionCatch
 * @Description 全局异常捕获
 * @Author leizhang
 * Date 2020/9/19 10:30 上午
 * @Version 1.0
 **/
@ControllerAdvice
public class ExceptionCatch {
    private static final Logger log = LoggerFactory.getLogger(ExceptionCatch.class);

    //不可预知异常集合
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;

    protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();

    static {
        //在这里加入一些基础的异常类型判断
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALIDPARAM);
    }

    /**
     * @param customException
     * @return com.xuecheng.framework.model.response.ResponseResult
     * @Description : 自定义异常捕获
     * @Author : leizhang
     * @Date 6:55 下午 2020/6/26
     **/
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult customException(CustomException customException) {
        log.error("catch exception : {}\r\nexception: ", customException.getMessage(), customException);
        ResultCode resultCode = customException.getResultCode();
        ResponseResult responseResult = new ResponseResult(resultCode);
        return responseResult;
    }

    /**
     * @param
     * @return com.xuecheng.framework.model.response.ResponseResult
     * @Description :不可预知异常捕获
     * @Author : leizhang
     * @Date 7:00 下午 2020/6/26
     **/
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception exception) {
        log.error("catch exception : {}\r\nexception: ", exception.getMessage(), exception);
        if (EXCEPTIONS == null) {
            EXCEPTIONS = builder.build();
        }
        final ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        final ResponseResult responseResult;
        if (resultCode == null) {
            //返回全局异常
            responseResult = new ResponseResult(CommonCode.SERVER_ERROR);
        } else {
            //返回定义的异常code码
            responseResult = new ResponseResult(resultCode);
        }
        return responseResult;
    }
}
